#include<stdio.h>
#include<windows.h>
#include"record.h"
#include"play.h"
#include"thread_lib.h"
#include"constants.h"

HANDLE create_thread(LPTHREAD_START_ROUTINE lpStartAddress,SOCKET sock, DWORD* p_threadId)
{
	HANDLE hThread = CreateThread(NULL, 0, lpStartAddress, (LPVOID)sock, 0, p_threadId);   
	if(hThread   ==   NULL)
	{   
		printf("CreateThread() failed:  %d\n", GetLastError());   
		return NULL;
	}   
	return hThread;
}


DWORD WINAPI voice_record_thread_runner(LPVOID lpParam)   
{
	SOCKET sock=(SOCKET)lpParam; 
	MSG   msg;
	LPWAVEHDR lpHdr;

	if(openMicAndStartRecording(GetCurrentThreadId()) < 0 ) return -1;
	
	while(GetMessage(&msg, 0, 0, 0)){
		switch(msg.message){
			case MM_WIM_DATA:
				lpHdr = (LPWAVEHDR)msg.lParam;
				waveInUnprepareHeader(getRecordHandler(), lpHdr, sizeof(WAVEHDR));

				if(lpHdr->lpData!=NULL )
				{
					if( SOCKET_ERROR == send(sock, lpHdr->lpData, lpHdr->dwBufferLength, 0))
					{
						printf("Send failed!\n");
					}

				}
				waveInPrepareHeader(getRecordHandler(),lpHdr, sizeof(WAVEHDR));
				waveInAddBuffer(getRecordHandler(), lpHdr, sizeof(WAVEHDR));

				break;
			default:
			//	printf("Unhandled msg id=%d\n", msg.message);
				break;
		}
	}

    return 0;
}  


DWORD WINAPI voice_play_thread_runner(LPVOID   lpParam)   
{   
	SOCKET sock=(SOCKET)lpParam;   
	char szBuff[DEFAULT_BUFFER];   
	int ret;
	if( 0 != startPlaying(GetCurrentThreadId() )  )
	{
		printf("Start Playing Failed!\n");
		return -1;
	}

	while(1)   
	{   
		ret = recv(sock, szBuff, DEFAULT_BUFFER, 0);   
		if   (ret   ==   0) 
		{
			printf("receive failed\n");
			break;
		}
		else  if(ret == SOCKET_ERROR)   
		{   
			printf("recv()  failed:  %d\n",   WSAGetLastError()); 
			closesocket(sock);  
			break;   
		}   
	
	
		if( 0 != playWavData(szBuff, ret))
		{
			printf("Playing Wave Data Failed!\n");
			break;
		}
	}   
	waveOutReset(g_playHandler);
	waveOutClose(g_playHandler);
	return   0;   
} 

